# 转换范围: 0 ~ 9999

class String_conversion_value
  attr_reader :str
  attr_reader :str_length
  attr_reader :str_array
  attr_reader :value

  def initialize(str = nil)
    new_str(str)
  end

  def new_str(string)   # 二次初始化方法
    if string
      @str = string
      @str_length = string.length
      @str_array = []
      @value = 0
    end
  end

  def han2num()
    @str_array = []
    string_array()
    a = "一二三四五六七八九"
    b = "千百十"
    sum = 0
    sum_t = 1
    
    @str_array.each_with_index{ |s, i|
      s.each_char{ |s_a|
        if a.include?(s_a)
          sum_t = (a.index(s_a))+1
          sum += sum_t if (i == (@str_array.size)-1) && (s.length == 1)
        elsif b.include?(s_a)
          case s_a
          when "千"
            sum += (sum_t * 1000)
          when "百"
            sum += (sum_t * 100)
          when "十"
            sum += (sum_t * 10)
          end
        end
      }
    }

    @value = sum
  end

  private                   # 以下方法类实例不可使用

  def string_array()
    str = ""
    position = ""           # 记录当前位数
    a = "一二三四五六七八九"
    b = "千百十"
    c = "零"
    d = "两"

    @str.each_char.each_with_index{ |x, y|
      if a.include?(x)
        str << down_conversion(y, position, x)
      elsif b.include?(x)
        str << x
        position = x
        @str_array << str
        str = ""
      elsif x == c
        position = ""
      elsif x == d
        str << "二"
      end
    }
  end

  def down_conversion(index_str, position, str)
    if index_str == (@str_length-1) 
      case position
      when "十"
        @str_array << str
        return ""
      when "百"
        @str_array << str + "十"
        return ""
      when "千"
        @str_array << str + "百"
        return ""
      when ""
        @str_array << str
        return ""
      else
      end

    else
      return str
    end
  end
end